const koa = require('koa')
const app = new koa()
const path = require('path')
const routing = require('./routers')
const koaBody = require('koa-body')
const koaStatic = require('koa-static')
const error = require('koa-json-error')
const parameter = require('koa-parameter')
const mongoose = require('mongoose')
const {
    connectStr
} = require('./config')

mongoose.connect(connectStr, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}, () => {
    console.log('Mongo数据库连接成功')
})
mongoose.connection.on('error', console.error)

app.use(koaStatic(path.join(__dirname, 'public')))

app.use(koaBody({
    multipart: true, // 开启文件格式解析
    formidable: {
        uploadDir: path.join(__dirname, '/public/uploads'), // 文件保存路径
        keepExtensions: true // 是否保留后缀名
    }
}))

app.use(error({
    postFormat: (e, {
        stack,
        ...rest
    }) => process.env.NODE_ENV === 'production' ? rest : {
        stack,
        ...rest
    }
}))
app.use(parameter(app))

routing(app)

app.listen(3001, () => {
    console.log('服务运行成功，地址是：http://localhost:3001')
})